import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime

# ===== 1. 模拟数据集（2000条用户行为记录） =====
np.random.seed(42)
data = {
    "user_id": np.arange(1000, 3000),
    "visit_date": pd.date_range('2025-06-01', periods=2000, freq='H'),
    "visit": np.random.choice([0, 1], size=2000, p=[0.1, 0.9]),
    "click": np.random.choice([0, 1], size=2000, p=[0.4, 0.6]),
    "add_to_cart": np.random.choice([0, 1], size=2000, p=[0.7, 0.3]),
    "payment": np.where(np.random.rand(2000) > 0.85, 1, 0),  # 15%支付转化率
    "order_amount": np.round(np.abs(np.random.normal(100, 40, 2000)), 2)
}
df = pd.DataFrame(data)

# ===== 2. 数据清洗与预处理 =====
# 删除从未访问的用户（Pandas布尔索引）
df = df[df['visit'] == 1]  

# 修正异常订单金额（Numpy条件逻辑）
df['order_amount'] = np.where(
    df['order_amount'] > 500, 
    500, 
    np.where(df['order_amount'] < 10, 10, df['order_amount'])
)

# 提取关键时间特征（Pandas日期处理）
df['visit_hour'] = df['visit_date'].dt.hour
df['visit_day'] = df['visit_date'].dt.day_name()

# ===== 3. 漏斗转化分析（中等复杂度核心） =====
funnel_steps = ['visit', 'click', 'add_to_cart', 'payment']
funnel_data = []

for step in funnel_steps:
    step_count = df[step].sum()
    funnel_data.append(step_count)
    
conversion_rates = [
    funnel_data[i+1] / funnel_data[i] 
    for i in range(len(funnel_data)-1)
]

# ===== 4. RFM用户分层（Pandas聚合+分箱） =====
current_date = datetime(2025, 7, 10)
rfm = df.groupby('user_id').agg(
    Recency=('visit_date', lambda x: (current_date - x.max()).days),
    Frequency=('visit_date', 'count'),
    Monetary=('order_amount', 'sum')
)

# 分箱赋值（中等复杂度分群逻辑）
rfm['R_Score'] = pd.qcut(rfm['Recency'], 4, labels=range(4, 0, -1))
rfm['F_Score'] = pd.qcut(rfm['Frequency'], 4, labels=range(1, 5))
rfm['M_Score'] = pd.qcut(rfm['Monetary'], 4, labels=range(1, 5))
rfm['RFM_Score'] = rfm['R_Score'].astype(str) + rfm['F_Score'].astype(str) + rfm['M_Score'].astype(str)

# 定义用户价值层级（业务规则映射）
segment_map = {
    r'[4][4-5].*': '高价值用户',
    r'[3-4][3-5].*': '潜力用户',
    r'[1-2][1-2].*': '流失风险用户',
    r'.*': '一般用户'
}
rfm['Segment'] = rfm['RFM_Score'].replace(segment_map, regex=True)

# ===== 5. 可视化分析 =====
plt.figure(figsize=(15, 5))

# 漏斗可视化
plt.subplot(121)
plt.bar(funnel_steps, funnel_data, color='skyblue')
for i, v in enumerate(funnel_data):
    plt.text(i, v+20, f"{v}", ha='center')
plt.title('用户行为漏斗分析(总样本:2000)')
plt.ylabel('用户数量')

# RFM分层分布
plt.subplot(122)
segment_counts = rfm['Segment'].value_counts()
plt.pie(segment_counts, labels=segment_counts.index, autopct='%1.1f%%')
plt.title('RFM用户价值分层')
plt.tight_layout()
plt.savefig('funnel_rfm_analysis.png')